<?php
// +----------------------------------------------------------------------------
// | Tke团队版权所属 [三十年河东三十年河西,莫欺少年穷.!]
// +----------------------------------------------------------------------------
// | Copyright (c) 2014 http://www.itdaodan.com All rights reserved.
// +----------------------------------------------------------------------------
// | Author: sap<songaiping@hrbjjhh.com>
// +----------------------------------------------------------------------------

namespace Admin\Model;
/**
 * @todo 客服管理
 * @since 2015-9-6
 */
class ServiceManageModel{
	
	public $error;//记录最后一次错误信息

	/**
	 * @todo 名单类别
	 * @author sap
	 * @since 2015-9-7
	 */
	public function rosterCategoryList($where = array(),$field= '',$orderby='roster_category_id asc'){
		return M('ServiceRosterCategory')->where($where)->field($field)->order($orderby)->select();
	}
	
	/**
	 * @todo 类别详情
	 * @author sap
	 * @since 2015-9-7
	 */
	public function rosterCategoryShow($base = array(),$field=''){
		$map = array();//初始化查询条件
		$map['status'] = array('gt',-1);
		if(!empty($base)){
			$map = array_merge($map,$base);
		}
		return M('ServiceRosterCategory')->where($map)->field($field)->find();
	}
	
	/**
	 * @todo   VIP状态修改
	 * @param  $id     express_detail_id
	 */
	public function vipRefuse($id, $status = 0){
	    if(empty($id) || $status == 0){
	        return false;
	    }
	    $where['express_detail_id'] = array('in', $id);
	    return M('service_express_detail')->where($where)->setField('mail_status', $status);
	}
	
	/**
	 * @todo   获取客户信息  
	 * @param  int     customer_id
	 */
	public function getServiceCustomerInfo($customer_id){
	    if($customer_id == 0){
	        return null;
	    }
	    //房屋信息+装修需求
	    return D('DemandHouseView')->field(true)->where(array('customer_id' => $customer_id))->find();
	}
	
	/**
	 * @todo   获取报名信息
	 * @param  int     customer_id
	 * @param  int     activity_id
	 */
	public function getServiceActivityInfo($customer_id, $activity_id){
	    if($activity_id == 0 || $customer_id == 0){
	        return null;
	    }
	    $where['activity_id'] = $activity_id;
	    $where['customer_id'] = $customer_id;
	    //报名信息
	    $join = M('service_activity_join')->field('join_time,customer_level')->where($where)->find();
	    //班车需求
	    $bus = M('service_activity_join_bus_demand')->field('bus_point_id,departure_time_id,people_num')->where($where)->find();
	    return ($join && $bus)? array_merge($join, $bus) : null ;
	}
	
	/**
	 * @todo 名单详情（一条）
	 * @author sap
	 */
	public function rollCallShow($roll_call_id=0,$field=''){
		//获取数据
		$roll_call_id = (int)$roll_call_id;
		if($roll_call_id == 0){
			$this->error = '参数丢失';
			return false;
		}
		//查询条件
		$map = array();//初始化查询条件
		$map['roll_call_id'] = $roll_call_id;
		//返回值
		return M('ServiceRollCall')->where($map)->field($field)->find();
	}
	
	/**
	 * @todo 通过ID读取文件地址
	 * @author sap
	 */
	public function fileShow($file_id){
		$file_id = (int)$file_id;
		if($file_id == 0){
			$this->error = '文件丢失';
			return false;
		}
		$map = array();
		$map['id'] = $file_id;
		$file_info = M('File')->where($map)->find();
		return C('DOWNLOAD_UPLOAD.rootPath').$file_info['savepath'].$file_info['savename'];
	}

	/**
	 * @todo 导入名单
	 * @author sap
	 */
	public function addRollCall(){
		//获取数据 - 基础判断
		$file_id = (int)I('file_id');
		$roster_category_id = (int)I('roster_category_id');
		$roll_call_name = strip_tags(I('roll_call_name'));
		$province_id = 0;
		$city_id = 0;
		$ward_id = 0;
		$village_id = 0;
		if($roll_call_name == '' || $roll_call_name == null || $file_id==0 || $roster_category_id==0 ){
			$this->error='参数丢失';
			return false;
		}
		$roster_category_show = $this->rosterCategoryShow(array('roster_category_name'=>'小区'),'roster_category_id');//小区类别信息
		$roster_category_village_id = $roster_category_show['roster_category_id'];
		//当选择小区类别时，获取省市区小区内容
		if($roster_category_id == $roster_category_village_id){
			$province_id = (int)I('province_id');
			$city_id = (int)I('city_id');
			$ward_id = (int)I('ward_id');
			$village_id = (int)I('village_id');
			if($province_id == 0 || $city_id == 0 || $ward_id == 0 || $village_id == 0){
				$this->error = '小区信息必须选择';
				return false;
			}
		}
		//文件地址
		$file_url = $this->fileShow($file_id);
		if(empty($file_url)){
			$this->error = $this->getError();
			return false;
		}
		
		set_time_limit (0);//程序执行时间
		//导入phpExcel核心类
		import( "Common.Msj.PHPExcel.PHPExcel.IOFactory" ,'' ,'.php' );
		$objReader = \PHPExcel_IOFactory::createReader('CSV');
		$objReader->setDelimiter(',');//默认的分隔符  
		$objReader->setInputEncoding('GBK');//默认的输入字符集    
		if(!$objReader->canRead($file_url)){
			$this->error = '生成失败! 无法读取该文件数据';
			return false;
		}
		$objPHPExcel = $objReader->load ($file_url);
		$sheet = $objPHPExcel->getSheet (0);
		$highestRow = $sheet->getHighestRow (); // 取得总行数
		
		//添加判断 导入总用户数不得大于3000千条
		if($highestRow > 3001){
			$this->error = '导入用户总数不得大于3000条';
			return false;
		}
		if($highestRow < 2){
			$this->error = '空文件';
			return false;
		}
		
		$data_add = array(); //添加数据初始化
		$arr = array(); //手机号数组初始化
		$error_num = 0; //失败总数
		$error_phone = 0; //格式失败总数
		
		for($j = 2; $j <= $highestRow; $j ++) {
			$mobile_phone = (string)$objPHPExcel->getActiveSheet()->getCell("B" .$j)->getValue();//手机号
			//判断手机号是否在数组中 并 判断手机号是否为11位
			//避免臧数据进入数据库,我再次修改 
			//@authoer Msj
			if(in_array($mobile_phone,$arr) || !preg_match("/^1[3-8][0-9]{9}$/", $mobile_phone)){
				$error_phone  = $error_phone+1;
				$error_num = $error_num+1;
				continue;
			}
			$arr[]= $mobile_phone;
			$key = $j - 2; //添加数组，键
			$data_add[$key]['customer_name'] = (string)$objPHPExcel->getActiveSheet()->getCell("A" .$j)->getValue();//姓名
			$data_add[$key]['mobile_phone'] = $mobile_phone;//手机号
			$data_add[$key]['decoration_meter'] = (float)$objPHPExcel->getActiveSheet()->getCell("C" .$j)->getValue();//平米
			//固定字段
			$data_add[$key]['province_id'] = $province_id;
			$data_add[$key]['city_id'] = $city_id;
			$data_add[$key]['ward_id'] = $ward_id;
			$data_add[$key]['village_id'] = $village_id;
		}
		if(empty($data_add)){
			$this->error = '空文件';
			return false;
		}
		
		//新建名单
		$data_roll_cal['roll_call_name'] = $roll_call_name;
		$data_roll_cal['roster_category_id'] = $roster_category_id;
		$data_roll_cal['village_id'] = $village_id;
		$data_roll_cal['ward_id'] = $ward_id;
		$data_roll_cal['city_id'] = $city_id;
		$data_roll_cal['province_id'] = $province_id;
		$data_roll_cal['create_user_id'] = UID;
		$data_roll_cal['create_time'] = NOW_TIME;
		$roll_call_id = M('ServiceRollCall')->add($data_roll_cal);
		if(!$roll_call_id){
			\Think\Log::write('名单导入：名单生成失败');
			$this->error = '导入失败，请重试1';
			return false;
		}
		//记录行为
		action_log('roll_call_add', 'service_roll_call', $roll_call_id, UID);
		
		//根据名单导入数据进行注册写入
		$obj_customer  = D('Admin/Customer');
		$res_list = $obj_customer->importCustomer($arr);
		if($res_list === false){
			\Think\Log::write('名单导入：名单生成成功，用户导入主表失败');
			$this->error = $obj_customer->getError();
			return false;
		}
		if($res_list['status'] == 0){
			//全部重复时，删除空名单 
			M('ServiceRollCall')->where(array('roll_call_id'=>$roll_call_id))->save(array('status'=>'-1'));
			//返回值
			$result = array(
					'count_num' => $highestRow-1,
					'error_num' => $highestRow-1,
					'error_phone_num' => $error_phone,
					'success_num' => '0',
			);
			return $result;
		}
		$error_num = $error_num + (count($arr) - $res_list['data']['num']);//计算重复数据数
		$customer_list = $res_list['data']['data'];//写入主表数据
		
		//成功添加客户数组循环
		$data_array = array();//临时数组
		foreach ($customer_list as $k=>$v){
			$data_array[$v['mobile_phone']] = $v;
		}
		//要添加数据
		$data = array();//要添加的数组
		foreach ($data_add as $key=>$val){
			if(isset($data_array[$val['mobile_phone']])){
				$data[$key] = $val;
				$data[$key]['customer_id'] = $data_array[$val['mobile_phone']]['customer_id'];
				$data[$key]['roll_call_id'] = $roll_call_id;
			}
		}
		$data = array_merge($data);//待导入数据
		
		//名单和用户的关系（名单中有哪些用户）
		if(M('service_roll_call_customer')->insertIgnoreAddAll($data) === false){
			\Think\Log::write('名单导入：用户导入成功，名单生成成功，名单中有哪些用户写入失败,名单ID'.$roll_call_id);
			$this->error = '导入失败，请重试2';
			return false;
		}
		//用户信息表service_customer_detail
		if(M('service_customer_detail')->insertIgnoreAddAll($data) === false){
			\Think\Log::write('名单导入：用户导入成功，名单生成成功，用户信息表写入失败,名单ID'.$roll_call_id);
			$this->error = '导入失败，请重试3';
			return false;
		}
		//用户的房产信息service_customer_house
		if($roster_category_id == $roster_category_village_id){
			if(M('service_customer_house')->insertIgnoreAddAll($data) === false){
				\Think\Log::write('名单导入：用户导入成功，名单生成成功，用户房产信息表写入失败,名单ID'.$roll_call_id);
				$this->error = '导入失败，请重试4';
				return false;
			}
		}
		$success_num = $highestRow - 1 - $error_num;//成功导入人数
		if(M('ServiceRollCall')->where(array('roll_call_id'=>$roll_call_id))->save(array('total_num'=>$success_num)) === false){
			\Think\Log::write('名单导入：用户导入成功，名单生成成功，名单导入成功总数写入失败,名单ID'.$roll_call_id);
			$this->error = '导入失败，请重试5';
			return false;
		}
		
		//清除缓存
		S('service_customer_house_detail',null);
		S('service_customer_house',null);
		S('service_customer_detail',null);
		S('service_roll_call_list',null);
		S('service_roll_call_customer_list',null);
		//返回值
		$result = array(
				'count_num' => $highestRow - 1,
				'error_num' => $error_num,
				'error_phone_num' => $error_phone,
				'success_num' => $success_num,
		);
		return $result;
	}
	
	/**
	 * @todo 名单详情
	 * @author sap
	 */
	public function infoRollCall($roll_call_id = 0){
		//获取数据
		$roll_call_id = (int)$roll_call_id;
		if($roll_call_id == 0){
			$this->error = '参数丢失';
			return false;
		}
		$result = S('service_roll_call_count_'.$roll_call_id);
		if(!empty($result)){
			return $result;
		}
		
		$where = array();//查询初始化
		$where['roll_call_id'] = $roll_call_id;
		$where['status'] = array('gt',-1);
		$count_num = M('ServiceRollCall')->where($where)->field('roll_call_name,total_num')->find();//导入客户
		if(empty($count_num)){
			$this->error = '请正确操作';
			return false;
		}
		
		$obj = M('ServiceRollCallCustomer');//名单和用户的关系表
		$result = array();//返回值初始化

		//无效用户 --- (√)
		$map = array();
		$map['roll_call_id'] = $roll_call_id;
		$map['is_valid'] = 1;//0-有效,1-无效
		$result['is_valid_num'] = $obj->where($map)->count();
		
		//绑定并有效用户 --- (√)
		$map = array();
		$map['roll_call_id'] = $roll_call_id;
		$map['is_valid'] = 0;//0有效
		$map['is_bind'] = 1;//1绑定
		$result['bind_member_num'] = $obj->where($map)->count();
		
		//未拨打   --- 未拨打中也有可能存在 持有人(√)
		$map = array();
		$map['roll_call_id'] = $roll_call_id;
		$map['is_call'] = 0;//0未拨打
		$map['is_valid'] = 0;//0有效
		$map['is_bind'] = 0;//0未绑定
		$result['not_is_call_num'] = $obj->where($map)->count();
		
		//持有中用户并有效并未绑定(稍后拨打或未拨打或已拨打)
		$map = array();
		$map['roll_call_id'] = $roll_call_id;
		$map['is_valid'] = 0;//0-有效
		$map['is_bind'] = 0;//没有绑定人
		$map['hold_member_id'] = array('gt',0);
		$result['hold_member_num'] = $obj->where($map)->count();
		
		
		//可拨打
		$map = array();
		$map['roll_call_id'] = $roll_call_id;
		$map['is_call'] = array('in','0,1');
		$map['is_valid'] = 0;//0-有效
		$map['is_bind'] = 0;//没有绑定人
		$result['is_not_call_num'] = $obj->where($map)->count();
		
		//已拨打
		$map = array();
		$map['roll_call_id'] = $roll_call_id;
		$map['is_call'] = 2;//0-未拨打，1-稍后拨打，2-已拨打
		$map['is_valid'] = 0;//0-有效,1-无效
		$result['is_call_num'] = $obj->where($map)->count();//已拨打 = 已经拨打&有效

		//导入用户数
		$result['count_num'] = $count_num['total_num'];
		//未绑定并有效用户
		$result['bind_not_member_num'] = $result['count_num'] - $result['bind_member_num'] - $result['is_valid_num'];
		
		$result['roll_call_id'] = $roll_call_id;
		$result['roll_call_name'] = $count_num['roll_call_name'];//名单名称
		
		S('service_roll_call_count_'.$roll_call_id,$result,3600);
		return $result;
	}
	
	/**
	 * @todo 配置可抢占人员
	 * @author sap
	 */
	public function setRollCallMember($roll_call_id,$member_id){
		//获取判断
		$roll_call_id = array_filter(array_unique((array)$roll_call_id));
		$member_id = array_filter(array_unique((array)$member_id));
		if(empty($roll_call_id) || empty($member_id)){
			$this->error='请正确操作';
			return false;
		}
		//新加数据
		$data = array();$key = 0;
		foreach ($roll_call_id as $val){
			foreach ($member_id as $v){
				$data[$key]['member_id'] = $v;
				$data[$key]['roll_call_id'] = $val;
				$key++;
			}
		}
		M()->startTrans();
		//删除原有
		$obj = M('ServiceRollCallMember');
		if($obj->where(array('roll_call_id'=>array('in',$roll_call_id)))->delete() === false){
			$this->error = $obj->getDbError();
			return false;
		}
		//新增操作
		if($obj->insertIgnoreAddAll($data) === false){
			M()->rollback();
			$this->error = $obj->getDbError();
			return false;
		}
		M()->commit();
		S('service_roll_call_member_list',null);
		S('service_member_roll_call_list',null);
		return true;
	}
	
	/**
	 * @todo 清空坐席持有资源
	 * @author sap
	 */
	public function delRollCallCustomerMember($member_id=array()){
		$member_id = array_filter(array_unique((array)I('member_id',0)));
		if(empty($member_id)){
			$this->error = '请选择座席';
			return false;
		}
		$map = array(); $data = array();
		$map['hold_member_id'] = array('in',$member_id);
		$data['is_call'] = 0;
		$data['hold_member_id'] = 0;
		if(M('ServiceRollCallCustomer')->where($map)->save($data) === false){
			$this->error = '操作失败';
			return false;
		}
		return true;
	}
	
	/**
	 * @todo 根据条件查询抢占人员
	 */
	public function rollCallMemberList($roll_call_id){
		return $member_list = M('ServiceRollCallMember')->where(array('roll_call_id'=>array('in',$roll_call_id)))->select();
	}
	
	/**
	 * @todo 名单下未绑定有效且未持有客户总数
	 * @param array $roll_call_id 名单ID数组
	 * @author sap
	 */
	public function rollCallCustomer($roll_call_id){
		$roll_call_id = array_filter(array_unique((array)$roll_call_id));
		if(empty($roll_call_id)){
			$this->error = '请正确操作';
			return false;
		}
		$map = array();
		$map['roll_call_id'] = array('in',$roll_call_id);
		$map['is_bind'] = 0;//未绑定
		$map['is_valid'] = 0;//有效
		$map['hold_member_id'] = 0;//未持有
		return M('ServiceRollCallCustomer')->where($map)->count();
	}
	
	/**
	 * @todo 生成数+1
	 * @author sap
	 */
	public function changeRollCallStatus($roll_call_id=0){
		$roll_call_id = (int)$roll_call_id;
		if($roll_call_id == 0){
			$this->error = '参数丢失';
			return false;
		}
		$map = array();
		$map['roll_call_id'] = $roll_call_id;
		M('service_roll_call')->where($map)->setInc('build_num',1); 
	}
	
	
	/**
	 * @todo 返回最后一次错误信息
	 * @return string
	 * @author PHP@妖孽 <dino_ma@163.com>
	 */
	public function getError(){
		return $this->error;
	}

}
